package com.tensquare.user.web.controller;

import java.util.HashMap;
import java.util.Map;

import dto.StatusCode;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import com.tensquare.user.po.User;
import com.tensquare.user.service.UserService;

import dto.PageResultDTO;
import dto.ResultDTO;
import utils.JwtUtil;

import javax.servlet.http.HttpServletRequest;

/**
 * 控制器层
 *
 * @author BoBoLaoShi
 */
@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private HttpServletRequest request;

    /**
     * 修改
     *
     * @param user
     */
    @PutMapping("/{id}")
    public ResultDTO edit(@RequestBody User user, @PathVariable String id) {
        user.setId(id);
        userService.updateUser(user);
        return new ResultDTO(true, StatusCode.OK, "修改成功");
    }

    /**
     * 删除
     *
     * @param id
     */
    @DeleteMapping("/{id}")
    public ResultDTO remove(@PathVariable String id) {
        // 先鉴权
        // 获取admin_claims对象
        Claims admin_claims = (Claims) this.request.getAttribute("admin_claims");
        if (admin_claims == null) {
            // 如果request没有admin_claims对象，说明不是admin角色，直接返回权限不足
            return new ResultDTO(false, StatusCode.ACCESSERROR, "权限不足");
        }
        userService.deleteUserById(id);
        return new ResultDTO(true, StatusCode.OK, "删除成功");
    }

    /**
     * 查询全部数据
     *
     * @return
     */
    @GetMapping
    public ResultDTO list() {
        return new ResultDTO(true, StatusCode.OK, "查询成功", userService.findUserList());
    }

    /**
     * 根据ID查询
     *
     * @param id ID
     * @return
     */
    @GetMapping("/{id}")
    public ResultDTO listById(@PathVariable String id) {
        return new ResultDTO(true, StatusCode.OK, "查询成功", userService.findUserById(id));
    }

    /**
     * 根据条件查询
     *
     * @param searchMap
     * @return
     */
    @PostMapping("/search")
    public ResultDTO list(@RequestBody Map searchMap) {
        return new ResultDTO(true, StatusCode.OK, "查询成功", userService.findUserList(searchMap));
    }

    /**
     * 分页+多条件查询
     *
     * @param searchMap 查询条件封装
     * @param page      页码
     * @param size      页大小
     * @return 分页结果
     */
    @PostMapping("/search/{page}/{size}")
    public ResultDTO listPage(@RequestBody Map searchMap, @PathVariable int page, @PathVariable int size) {
        Page<User> pageResponse = userService.findUserListPage(searchMap, page, size);
        return new ResultDTO(true, StatusCode.OK, "查询成功", new PageResultDTO<User>(pageResponse.getTotalElements(), pageResponse.getContent()));
    }

    /**
     * 发送短信验证
     */
    @PostMapping("/sendsms/{mobile}")
    public ResultDTO sendCheckCode(@PathVariable String mobile) {
        this.userService.saveSmsCheckcode(mobile);
        return new ResultDTO(true, StatusCode.OK, "发送成功");
    }

    /**
     * 注册
     */
    @PostMapping("/register/{checkcode}")
    public ResultDTO register(@RequestBody User user, @PathVariable String checkcode) {
        this.userService.saveUser(user, checkcode);
        return new ResultDTO(true, StatusCode.OK, "用户注册成功");
    }

    /**
     * 登陆
     */
    @PostMapping("/login")
    public ResultDTO login(@RequestBody User loginUser) {
        User user = this.userService.findByMobileAndPassword(loginUser.getMobile(), loginUser.getPassword());
        if (user == null) {
            // 登陆失败
            return new ResultDTO(false, StatusCode.LOGINERROR, "账号或密码有误");
        }

        // 生成jwt
        HashMap<String, Object> map = new HashMap<>();
        String token = this.jwtUtil.createJWT(user.getId(), user.getMobile(), "user");
        map.put("token", token);
        if (user.getNickname() != null && !"".equals(user.getNickname())) {
            map.put("name", user.getNickname());
        } else {
            map.put("name", user.getMobile());
        }
        // 放头像
        map.put("avatar", user.getAvatar());
        return new ResultDTO(true, StatusCode.OK, "登陆成功", map);
    }

    /**
     * 更新添加好友的粉丝数。同时增加自己的关注数
     * 因为是提供给后台调用的，所以不需要返回值
     */
    @RequestMapping(value = "/{userid}/{friendid}/{x}", method = RequestMethod.PUT)
    public void updateFansCountAndFollowCount(@PathVariable(name = "userid") String userid,
                             @PathVariable(name = "friendid") String friendid,
                             @PathVariable(name = "x") int x) {
        this.userService.updateFansCountAndFollowCount(userid, friendid,x);
    }


}
